from fastapi import APIRouter, Depends

from app_v2.AsyncDataBase import get_async_db_cursor
from app_v2.model import Attention

user = APIRouter(prefix="/user", tags=["user"])


# Benchmark 10ms
@user.get("/like")
async def user_like(uid: str, c1=Depends(get_async_db_cursor)):
    await c1.execute(f"SELECT mid FROM user_likes_up WHERE uid = %s; SELECT bvid FROM user_likes_video WHERE uid = %s",
                     [uid, uid])
    uids = await c1.fetchall()
    await c1.nextset()
    bvids = await c1.fetchall()
    return {
        "code": 200,
        "data": {
            "mids": [item["mid"] for item in uids],
            "bvids": [item["bvid"] for item in bvids],
        }
    }


@user.post("/like")
async def user_like_up(data: Attention, cursor=Depends(get_async_db_cursor)):
    if not data.mid and not data.bvid:
        return {
            "code": 401,
            "message": "bad request"
        }
    if data.mid:
        await cursor.execute("INSERT INTO user_likes_up (uid, mid) VALUES (%s, %s)", [data.uid, data.mid])

    if data.bvid:
        await cursor.execute("INSERT INTO user_likes_video (uid, bvid) VALUES (%s, %s)", [data.uid, data.bvid])

    return {
        "code": 200
    }


@user.delete("/like")
async def user_like_down(data: Attention, cursor=Depends(get_async_db_cursor)):
    if data.mid:
        await cursor.execute(
            "DELETE FROM user_likes_up WHERE uid = %s and mid = %s",
            [data.uid, data.mid]
        )

    if data.bvid:
        await  cursor.execute(
            "DELETE FROM user_likes_video WHERE  uid = %s and bvid = %s",
            [data.uid, data.bvid]
        )

    return {
        "code": 200,
    }
